from flask import request
from app.extensions import db
from app.models.model_mixin import BaseMixin
from datetime import datetime
from app.models.article import Article


# 专报
class Report(db.Model, BaseMixin):
    """params: status 9:默认未审核 8:已审核
    title:改为时间
    sub_title:期数
    report_person:抄送单位
    push_person:报告人
    edit_person:编校人员
    sign_issue:签发人员
    """
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    sub_title = db.Column(db.String(100))
    report_person = db.Column(db.String(100))
    push_person = db.Column(db.String(100))
    num = db.Column(db.Integer, default=1)
    edit_person = db.Column(db.String(100))
    sign_issue = db.Column(db.String(100))
    status = db.Column(db.Integer, default=9, index=True)
    desc = db.Column(db.String(200))
    file_url = db.Column(db.String(200))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    articles = db.relationship('Article', back_populates='report', order_by=lambda: Article.sort.desc())

    @classmethod
    def get_total_count(cls):
        """获取总期数"""
        return cls.query.count()

    @classmethod
    def get_hired_count(cls):
        """获取录用数"""
        return Article.query.filter(Article.rid != None, Article.status == 9).count()

    @classmethod
    def get_not_hired_count(cls):
        """获取未录用数"""
        return Article.query.filter(Article.rid == None, Article.status == 9).count()

    def to_dict(self):
        res_data = {
            'id': self.id,
            'title': self.title,
            'sub_title': self.sub_title,
            'report_person': self.report_person,
            'push_person': self.push_person,
            'num': self.num,
            'edit_person': self.edit_person,
            'sign_issue': self.sign_issue
        }
        if 'api_v1.report' in request.endpoint:
            res_data.update({
                'articles': [{'id': i.id, 'title': i.title, 'content': i.content} for i in self.articles]
            })
        return res_data

    @staticmethod
    def to_collection_dict(query, page, per_page=10):
        resources = query.paginate(page, per_page, False)
        data = {
            'items': [item.to_dict() for item in resources.items],
            '_meta': {
                'total_count': Report.get_total_count(),
                'hired_count': Report.get_hired_count(),
                'not_hired_count': Report.get_not_hired_count(),
                'page': page,
                'per_page': per_page,
                'total_pages': resources.pages,
                'total_items': resources.total
            }
        }
        return data
